package pc.nick.server.process;

import pc.nick.http.HttpServlet;
import pc.nick.http.HttpServletRequest;
import pc.nick.http.HttpServletResponse;
import pc.nick.http.ServletContext;

/**
 * 动态请求处理类
 */
public class DynamicProcessor implements Processor{
    @Override
    public void process(HttpServletRequest request, HttpServletResponse response) {
        // 1.假设请求地址为 /helle.action --> 对应的是hello 这个Servlet类
        // 从request中取出getRequestURI
        String uri = request.getRequestURI();
        // 2.去掉/及action两个部分，得到hello，再在后面拼接一个Servlet，就是helloServlet,就是servlet类名
        String servletName = uri.substring(1, uri.lastIndexOf(".")) + "Servlet";
        // 单实例实现 --> 到Map中判断是否已经存在了这个servlet实例，如果有，则取出这个实例
        // 利用反射来加载这个类的字节码 URLClassLoader 来加载class
        HttpServlet servlet = null;
        if(!ServletContext.servlets.containsKey(servletName)){
            try {
                Class<?> c = Class.forName("pc.nick.servlet." + servletName); // 反射：找到servlet目录下，名为helloServlet的类
                // 2.利用class实例化newInstance() -> servlet初始化
                Object obj = c.newInstance();
                // 将servlet放入ServletContext中
                ServletContext.servlets.put(servletName, (HttpServlet)obj);

                servlet = (HttpServlet)obj;
                servlet.init();
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }else{
            servlet = (HttpServlet) ServletContext.servlets.get(servletName);
        }
        servlet.service(request, response);
    }
}
